<template>
  <div class="pages">
    <div class="pageLevel" v-if="!sub">
      <div class="tableSearch">
        <el-form label-width="100px" size="mini">
          <el-form-item label="来源：" v-if="soUrce!='5'">
            <el-select v-model="selectdata.source" placeholder="请选择">
              <el-option label="全部来源" value></el-option>
              <el-option label="自主创建" value="0" ></el-option>
              <el-option label="上级分配" value="2" v-if="isShop=='0'"></el-option>
              <el-option label="下级自建" value="1" v-if="isShop=='1'"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="门店:" label-width="100px" v-if="isShop=='1'">
            <el-select
              size="small"
              filterable
              style="width:190px"
              v-model="selectdata.shopName"
              placeholder="请选择"
            >
              <el-option
                v-for="(item,index) in selectBaseShopPageLists"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label label-width="35px">
            <el-input v-model="selectdata.activityName" clearable placeholder="请输入活动名称搜索"></el-input>
          </el-form-item>
          <el-form-item label label-width="10px">
            <el-button type="primary" @click="searchSelect()">搜索</el-button>
          </el-form-item>
          <el-form-item label label-width="10px">
            <el-button type="primary" @click="addPrice('1')" v-if="setRole('新增/编辑')">新增变价方案</el-button>
          </el-form-item>
          <el-form-item label label-width="10px">
            <el-button type="primary" @click="_distribution(0)" v-if="setRole('分配')">分配</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table
          :data="priceList.tableData"
          stripe
          @selection-change="priceList.handleMultipleSelect"
          :row-key="getRowKeys"
          ref="multipleTables"
        >
          <el-table-column type="selection" :reserve-selection="true" :selectable="puStatus"  width="55" v-if="soUrce!='5'"></el-table-column>
          <el-table-column prop="activityName" label="方案名称" align="center"></el-table-column>
          <el-table-column label="活动时间" align="center" width="240">
            <template slot-scope="scope">
              <span>{{scope.row.activityStartTime}} —</span>
              <span>{{scope.row.activityEndTime}}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="soUrce!='5'"
            prop="activitySource"
            label="来源"
            align="center"
            :formatter="activitySource"
          ></el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-if="setRole('上下架')&&(scope.row.activityState=='0'||scope.row.activityState=='1')"
                v-model="scope.row.status"
                active-color="#13ce66"
                active-value="0"
                class="demo"
                inactive-value="1"
                active-text="上架"
                inactive-text="下架"
                @change="checkbox(scope.row.id,scope.row.status)"
              ></el-switch>
              <span v-if="scope.row.activityState=='2'">已过期</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="400">
            <template slot-scope="scope">
              <el-button size="mini" v-if="setRole('分配')" :disabled="scope.row.activitySource!='0'" @click="_distribution(1,scope.row.id,scope.row.activityName)" type="text">查看已分配</el-button>
              <el-button
                size="mini"
                @click="addpriceShop(1,scope.row)"
                v-if="setRole('新增/编辑')"
                :disabled="(scope.row.activityState=='2'||scope.row.activitySource!='0')"
                type="text"
              >新增变价商品</el-button>
              <el-button size="mini" v-if="setRole('新增/编辑')"   @click="addpriceShop(2,scope.row)" type="text">查看变价商品</el-button>
              <el-button
                size="mini"
                @click="addPrice(2,scope.row)"
                v-if="setRole('新增/编辑')"
                :disabled="(scope.row.activityState=='2'||scope.row.activitySource!='0')"
                type="text"
              >编辑</el-button>
              <el-button size="mini" v-if="setRole('新增/编辑')" :disabled="(scope.row.activitySource!='0'||scope.row.activityState=='2')"  @click="deleteRows(scope.$index,scope.row.id,scope.row.activityState)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <page-unit :pageData="priceList.pageData" :func="tableget"></page-unit>
      </div>
    </div>
    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
    <!-- 弹出框 -->
    <!-- 新增变价方案 -->
    <el-dialog
      title="新增|编辑变价方案"
      class="addshopname"
      :visible.sync="priceProgramme.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
     >
      <i class="el-icon-close icon" @click="resetForm('priceprogramme')"></i>
      <el-form
        ref="priceprogramme"
        :model="priceprogramme"
        size="mini"
        label-width="150px"
        :rules="rules"
        style="margin-top:20px;"
        label-position="left"
      >
        <el-form-item label="方案名称：" prop="schemeName" style="height:50px">
          <el-col :span="10">
            <el-input v-model="priceprogramme.schemeName" maxlength="30" clearable :disabled="!setRole('新增/编辑')"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="活动日期：" prop="dateRange" style="height:50px">
          <el-date-picker
            :disabled="!setRole('新增/编辑')"
            v-model="priceprogramme.dateRange"
            type="daterange"
            format="yyyy年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="截止日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态：" prop="status" style="height:50px">
          <el-col :span="8">
            <el-radio-group v-model="priceprogramme.status" :disabled="!setRole('新增/编辑')">
              <el-radio label="0">上架</el-radio>
              <el-radio label="1">下架</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item style="float:center;">
          <el-button
            type="primary"
            @click="onSubmit('priceprogramme')"
            style="float:center;margin-left:100px"
          >确定</el-button>
          <el-button @click="resetForm('priceprogramme')" style="float:center;margin-left:100px">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新增变价商品 -->
    <el-dialog
      :title="goodsTitle"
      :visible.sync="goodsClass.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
       class="addshopname"
     >
     <i class="el-icon-close icon" @click="cancelgoodsClass"></i>
      <el-form label-width="80px" class="demo-ruleForm">
        <el-col :span="12">
          <el-form-item label="商品名称:">
            <el-input
              class="input"
              v-model="dialogShop.shopName"
              size="small"
              placeholder="请输入商品名称或条码号搜索"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="商品品牌:">
            <el-select size="small" v-model="dialogShop.commodityBrand" placeholder="请先选择商品品牌">
              <el-option
                v-for="(item,index) in commodityBrandList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品分类:">
            <el-cascader
              size="small"
              change-on-select
              expand-trigger="hover"
              :options="commodityCategoryfunList"
              v-model="dialogShop.commodityCategory"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label label-width="20px">
            <el-button @click="dialogSearch()" size="small" type="primary">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <el-table :data="tableDatas" ref="multipleTablegood" tooltip-effect="dark" height="350">
        <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="barCode" label="条码号" align="center"></el-table-column>
        <el-table-column prop="goodsParameterList" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsParameterList" :key="index">
              <span v-if="item!=null">{{item.name}} :</span>
              <span v-if="item!=null">{{item.value}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" align="center"></el-table-column>
        <el-table-column prop="price" label="售价" align="center"></el-table-column>
        <el-table-column prop="memberPrice" label="会员价" align="center"></el-table-column>
        <el-table-column prop="activityPrice" width="150" label="优惠价" align="center" v-if="setRole('新增/编辑')&&((activitySources=='0'&&activityStates!='2'))">
         <!-- @input="watchInput(scope.row.price, scope.row.activityPrice, scope.$index)" -->
          <template slot-scope="scope">
            <el-input
              size="small"
              maxlength="8"
              style="width:120px;"
              v-model="scope.row.activityPrice"
              onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
              @blur="handleSelect(scope.row)"
            ></el-input>
            <!-- <sd-input @blur="handleSelect(scope.row)" :val.sync="scope.row.goodsCode"></sd-input> -->
          </template>
        </el-table-column>
         <el-table-column prop="activityPrice" label="优惠价" align="center" v-else>
          <template slot-scope="scope">
           <span>{{scope.row.activityPrice}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsCode" label="操作" align="center" v-if="setRole('新增/编辑')&&((addpriceShopType=='2'&&activitySources=='0'&&activityStates!='2'))">
          <template slot-scope="scope">
            <el-button type="text" @click="deletes(scope.$index, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <page-unit :pageData="goodsClass.pageData" :func="_findGoodsShopPage"></page-unit> -->
      <div class="pageblock">
          <!-- <el-button size="small" type="primary" class="topage1" @click="toPages">确定</el-button> -->
          <el-pagination @size-change="handleSizeChanges" @current-change="handleCurrentChanges" :current-page="currentPages" :page-sizes="[5,10,20]" :page-size="pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      <el-form label-width="0" size="mini" style="width:50%;margin:0 auto;text-align:center;">
        <el-form-item>
          <el-button type="primary" v-if="setRole('新增/编辑')&&((activitySources=='0')&&activityStates!='2')" @click="handleSelectGoods()" style="margin-right:60px;">保存</el-button>
          <el-button @click="cancelgoodsClass" v-if="setRole('新增/编辑')&&((activitySources=='0')&&activityStates!='2')" style="margin-right:20px;">取消</el-button>
          <el-button @click="goodsClass.dialog=false" v-else style="margin-right:20px;">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配和查看已分配 -->
    <el-dialog
      :title="Elastic"
      :visible.sync="distribution.dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
       class="addshopname"
     >
     <i class="el-icon-close icon" @click="Sub"></i>
      <div class="tableSearch">
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label label-width="15px">
            <el-input class="input" v-model="selectdatas.orgKey" size="small" placeholder="请输入商户名称"></el-input>
          </el-form-item>
          <el-form-item label label-width="15px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="searchSelectOrg"
              class="Button"
            >查询</el-button>
          </el-form-item>
          <el-form-item label label-width="15px">
            <el-button type="primary"  @click="cancel()" size="mini" v-if="unallocates&&setRole('分配')">批量取消分配</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="shopList"
        ref="multipleTable"
        max-height="300"
        @selection-change="distribution.handleMultipleSelect"
        :row-key="getRowKeys"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column property="name" label="门店名称" align="center"></el-table-column>
        <el-table-column property="shopCode" label="编号" align="center"></el-table-column>
        <el-table-column v-if="unallocates&&setRole('分配')" prop="name" align="center" label="操作" width="280">
          <template slot-scope="scope">
            <el-button size="small" @click="cancel(scope.row.id)" type="text"  class="addDetail">取消分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <page-unit :pageData="distribution.pageData" :func="_distributionlistPage"></page-unit> -->
      <div class="operationBox StoreBranch" style="margin-top:20px;">
        <el-button
          type="primary"
          @click="immediateAllocation"
          size="medium"
          v-if="!unallocates"
          style="margin-right:10px;"
        >立即分配</el-button>
        <el-button plain @click="Sub" size="medium">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import util from "@/util";
import state from "@/util/state";
import { TableHandle } from "@/util/class";
import pageUnit from "@/components/Page";
import sdInput from "@/components/SdInput";
import StoreBranch from "@/components/StoreBranch";
import {
  findActivityListPage,
  saveOrUpdateActivity,
  updateActivity,
  getGoodsListForMarket,
  getActivityDetail,
  markettoLowerShop,
  distributionShopList,
  cancelDistribution,
  offActivity,
  selectBaseShopPageList,
  selectByGoodsId,
  getGoodsClassifyTreeList,
  deleteActivityGoods,
  updateActivityGoods
} from "@/api";
export default {
  computed: mapState(["merchantId", "sub", "isStore","power","soUrce","isShop"]),
  components: { pageUnit, sdInput, StoreBranch },
  data() {
    return {
      getRowKeys(row) {
        return row.id; // 获取row的key值
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      activityStates: state.activityState, // 活动状态
      activitySource: state.activitySource, //来源
      multipleSelection: [],
      selectdata: {
        source: "",
        activityName: "",
        shopName: ""
      },
      tableDataCount: [], // 活动统计数组
      tableData: [],
      selectBaseShopPageLists: [], //门店列表
      priceList: new TableHandle(), // 商品变价列表
      priceProgramme: new TableHandle(), // 新增变价方案
      goodsClass: new TableHandle(), //新增变价商品
      distribution: new TableHandle(), //分配门店
      priceprogramme: {
        schemeName: "",
        dateRange: [],
        status: "0"
      }, //新增变价数据
      rules: {
        schemeName: [
          { required: true, message: "请输入方案名称", trigger: "blur" }
        ],
        dateRange: [
          { required: true, message: "请选择日期", trigger: "change" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }]
      },
      tableDatas: [],
      dialogShop: {
        shopName: "", //商品弹窗商品名称
        commodityBrand: "", //品牌
        commodityCategory: [""] //分类
      },
      commodityBrandList: [], //品牌数据
      commodityCategoryfunList: [], //分类数据
      Elastic: "",
      integralMulti: [],
      selectdatas: {
        orgKey: ""
      },
      unallocates: false,
      revise: [],
      priceId: "", //编辑方案时id
      addpriceShopType: "",
      addpriceShopId: "", //查看变价商品id
      shopList: [], //分配门店数组
      activityIds: "",
      nameType: "",
      idType:"",
      activityName:"",
      pageSizes: 10,
      total: 0,
      currentPages: 1,
      activityEndTime:"",
      activityStartTime:"",
      goodsTitle:"",//商品弹窗title
      activityStates:"",//状态
      activitySources:"",//来源
    };
  },
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this.tableget(this.priceList.pageData.pageSize, 1);
        }
      },
      deep: true
    }
  },
  mounted() {
    this.tableget(this.priceList.pageData.pageSize, 1);
    this.baseShopPageList();
  },
  methods: {
     // 监测商品输入数量不能大于库存数量
    // watchInput(price, activityPrice, index) {
    //       if(Number(activityPrice) > Number(price)) {
    //         this.$message.error('输入优惠价不能大于售价！')
    //         return
    //       }
    // },
    puStatus(row) {
      return row.activitySource == 0;
    },
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    // 门店列表
    baseShopPageList() {
      selectBaseShopPageList({
        businessId: this.merchantId,
        type: "3"
      }).then(res => {
        let a = {
          id: "",
          name: "全部"
        };
        res.data.list.unshift(a);
        this.selectBaseShopPageLists = res.data.list;
      });
    },
    // 获取表格数据
    tableget(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        pageNum: pageNum,
        companyId: this.merchantId,
        activityType: "5", //活动类型
        activityName: this.selectdata.activityName,
        shopId: this.selectdata.shopName,
        activitySource: this.selectdata.source,

      };
      findActivityListPage(data).then(res => {
        if (res.code == 200) {
          this.priceList.pageData.totalItems = parseInt(res.data.totalPage);
          this.priceList.pageData.currentPage=pageNum
          this.priceList.tableData = res.data.list;
         this.priceList.pageData.currentPage=pageNum
          for (let i = 0; i < this.priceList.tableData.length; i++) {
            this.priceList.tableData[i].activityStartTime = util.foryear(
              this.priceList.tableData[i].activityStartTime
            );
            this.priceList.tableData[i].activityEndTime = util.foryear(
              this.priceList.tableData[i].activityEndTime
            );
            this.priceList.tableData[i].status = String(
              this.priceList.tableData[i].status
            );
            if (this.priceList.tableData[i].status === "0") {
              this.priceList.tableData[i].sureStatus = true;
              this.priceList.tableData[i].sureDisable = false;
            } else if (this.priceList.tableData[i].status === "1") {
              this.priceList.tableData[i].sureStatus = false;
              this.priceList.tableData[i].sureDisable = true;
            }
          }
        }
      });
    },
    // 上下架状态
    checkbox(id, status) {
      this.$confirm("确定改变状态吗?", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      })
        .then(() => {
          if (status === "0") {
            this.delelist(id, "", "0");
          } else {
            this.delelist(id, "", "1");
          }
        })
        .catch(() => {
          this.tableget(this.priceList.pageData.pageSize, 1);
        });
    },
    // 点击查询按钮
    searchSelect() {
      this.tableget(this.priceList.pageData.pageSize, 1);
    },
    delelist(id, dr = "", status = "") {
      let data = {
        activityId: id,
        dr: dr,
        status: status
      };
      offActivity(data).then(res => {
        if (res.code == 200) {
          this.tableget(this.priceList.pageData.pageSize, 1);
          this.$message.success(res.msg);
        }else if(res.code=="10001"){
           this.$alert("同一活动时间内，同一商品不能出现在两个变价方案中~", res.msg, {
          confirmButtonText: '确定',
          center: true,
          callback: action => {
            this.tableget(this.priceList.pageData.pageSize, 1);
          }
          
         });
        }else {
          this.tableget(this.priceList.pageData.pageSize, 1);
        }
        
      });
    },
    // 删除一条活动
    deleteRows(i, id,activityState) {
      this.$confirm("确定要删除吗?", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).then(() => {
        if(activityState=='1'){
         this.$alert("变价方案已经启动，不能删除", {
          confirmButtonText: '确定',
          center: true,
          callback: action => {
           this.tableget(this.priceList.pageData.pageSize, 1);
          }
         });
        }else{
          this.delelist(id, 1);
        }
       
      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 新增变价方案
    addPrice(type, rows = "") {
      this.priceProgramme.dialog = true;
      if (type == "2") {
        this.priceprogramme.dateRange = [];
        this.priceprogramme.schemeName = rows.activityName;
        this.priceprogramme.dateRange.push(rows.activityStartTime);
        this.priceprogramme.dateRange.push(rows.activityEndTime);
        //  this.priceprogramme.dateRange[0]=rows.activityStartTime
        //  this.priceprogramme.dateRange[1]=rows.activityEndTime
        (this.priceprogramme.status = rows.status), (this.priceId = rows.id);
      } else {
        this.init();
      }
    },
    // 新增变价方案确定
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this._saveOrderPriceAgreement();
        } else {
          return false;
        }
      });
    },
    // 新增/编辑变价方案接口
    _saveOrderPriceAgreement() {
      let data = {
        orgId: this.merchantId,
        activityName: this.priceprogramme.schemeName,
        activityStartTime: this.priceprogramme.dateRange[0],
        activityEndTime: this.priceprogramme.dateRange[1],
        status: this.priceprogramme.status,
        activityType: "5",
        id: this.priceId,
        joinType:"1"
      };
      if (this.priceId == "") {
        saveOrUpdateActivity(data).then(res => {
          if (res.code == 200) {
            this.priceProgramme.dialog = false;
            this.init();
            this.tableget(
              this.priceList.pageData.pageSize,
              this.priceList.pageData.currentPage
            );
          }
        });
      } else {
        updateActivity(data).then(res => {
          if (res.code == 200) {
            this.priceProgramme.dialog = false;
            this.init();
            this.tableget(
              this.priceList.pageData.pageSize,
              this.priceList.pageData.currentPage
            );
          }
        });
      }
    },
    init() {
      this.priceprogramme.schemeName = "";
      this.priceprogramme.dateRange = [];
      this.priceprogramme.status = "0";
      this.priceId = "";
    },
    // 新增变价方案取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.priceProgramme.dialog = false;
    },
    // 点击新增变价商品按钮
    addpriceShop(type, rows) {
      if(type=="1"){
        this.goodsTitle="添加商品"
      }else{
        this.goodsTitle="查看变价商品"
      }
      this.revise=[]
      this.addpriceShopType = type;
      this.addpriceShopId = rows.id;
      this.activityStartTime = rows.activityStartTime;
      this.activityEndTime = rows.activityEndTime;
      this.activitySources = rows.activitySource;
      this.activityStates = rows.activityState;
      this.goodsClass.dialog = true;
      this._findGoodsShopPage(
        this.pageSizes,
        1,
        rows.id,
        rows.activityStartTime,
        rows.activityEndTime
      );
      this.commodityBrand();
      this.commodityCategoryfun();
    },
    // 新增变价商品列表
    _findGoodsShopPage(
      pageSize,
      pageNum,
      activityId = "",
      activityStartTime = "",
      activityEndTime = "",
     ) {
      let primaryClassifyId =
        this.dialogShop.commodityCategory[
          this.dialogShop.commodityCategory.length - 1
        ] || "";
      if (this.addpriceShopType == "1") {
        let data = {
          pageSize: pageSize,
          pageNo: pageNum,
          activityId: activityId,
          activityStartTime: activityStartTime,
          activityEndTime: activityEndTime,
          goodsKeywords: this.dialogShop.shopName,
          brandId: this.dialogShop.commodityBrand,
          classifyId: primaryClassifyId,
          activityType: "5",
          shopId: this.merchantId,
          isStore:this.isShop
        };
        getGoodsListForMarket(data).then(res => {
          this.tableDatas = res.data.list;
          this.total = res.data.total;
          for (let i = 0; i < this.tableDatas.length; i++) {
            for (let b = 0; b < this.revise.length; b++) {
              if (this.tableDatas[i].id === this.revise[b].id) {
                this.tableDatas[i] = this.revise[b];
              }
            }
          }
        });
      } else {
        let datas = {
          pageSize: pageSize,
          pageNum: pageNum,
          id: activityId,
          classifyId: primaryClassifyId,
          brandId: this.dialogShop.commodityBrand,
          goodsKeywords: this.dialogShop.shopName
        };
        getActivityDetail(datas).then(res => {
          this.tableDatas = res.data.goodsList;
          this.total = res.data.goodsTotal;
          for (let i = 0; i < this.tableDatas.length; i++) {
            for (let b = 0; b < this.revise.length; b++) {
              if (this.tableDatas[i].id === this.revise[b].id) {
                this.tableDatas[i] = this.revise[b];
              }
            }
          }
        });
      }
    },
    toPages() {
      this._findGoodsShopPage(this.pageSizes, this.currentPages,this.addpriceShopId,this.activityStartTime,this.activityEndTime);
    },
    handleSizeChanges(val) {
      this.pageSizes = val;
      this._findGoodsShopPage(this.pageSizes, this.currentPages,this.addpriceShopId,this.activityStartTime,this.activityEndTime);
    },
    handleCurrentChanges(val) {
      this.currentPages = val;
      this._findGoodsShopPage(this.pageSizes, this.currentPages,this.addpriceShopId,this.activityStartTime,this.activityEndTime);
      
    },
    unique(arr) {
      // 根据唯一标识no来对数组进行过滤
      const res = new Map(); //定义常量 res,值为一个Map对象实例 //返回arr数组过滤后的结果，结果为一个数组   过滤条件是，如果res中没有某个键，就设置这个键的值为1
      return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1));
    },
    handleSelect(row) {
      if (row.activityPrice!="") {
        this.revise.push(row);
        this.revise = this.unique(this.revise);
      }
    },
    deletes(index, id) {
      this.$confirm("要删除该条变价商品吗？", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).then(() => {
        deleteActivityGoods({
          activityGoodsId:id
        }).then(res=>{
           if(res.code=="200"){
             this._findGoodsShopPage(this.pageSizes, this.currentPages,this.addpriceShopId,this.activityStartTime,this.activityEndTime);
             this.$message.success(res.msg);
           }
        }) 
      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });;
    },
    // 商品品牌
    commodityBrand() {
      selectByGoodsId({
        shopId: this.merchantId,
        keyword: this.brandInfo,
        type: "0"
      }).then(res => {
        let a = {
          id: "",
          name: "全部"
        };
        res.data.list.unshift(a);
        this.commodityBrandList = res.data.list;
      });
    },
    // 商品品类
    commodityCategoryfun() {
      getGoodsClassifyTreeList().then(res => {
        let a = {
          value: "",
          label: "全部"
        };
        res.data.unshift(a);
        this.commodityCategoryfunList = res.data;
      });
    },
    dialogSearch() {
      this._findGoodsShopPage(this.pageSizes, this.currentPages,this.addpriceShopId,this.activityStartTime,this.activityEndTime);
    },
    // 商品弹窗确认选择
    handleSelectGoods() {
      this.revise.forEach(item => {
        item.goodsSpec = item.goodsParameterList;
      });
      let goodsList = this.revise;
      if (this.addpriceShopType == "1") {
        let data = {
          id: this.addpriceShopId,
          goodsList: JSON.stringify(goodsList),
          activityType: "5",
          operate: "0"
        };
        let priceNum=true
        goodsList.forEach(e=>{
           if(e.activityPrice=="0"){
             priceNum=false;
             return;
           }
        })
        if(priceNum==false){
           this.$message({
            type: "error",
            message: "请输入大于0的优惠价"
          });
        }else{
           updateActivity(data).then(res => {
          if (res.code == "200") {
            this.cancelgoodsClass()
          }
         });
        }
      } else {
        this.revise.forEach(i => {
          i.goodsSpec = i.goodsParameterList;
        });
        let goodsLists = this.revise;
        let data = {
          activityId: this.addpriceShopId,
          goodsList: JSON.stringify(goodsLists),
        };
        let a = true;
        this.tableDatas.forEach(ele => {
          if (ele.activityPrice === ""||ele.activityPrice=='0') {
            a = false;
            return;
          }
        });
        if (a == false) {
          this.$message({
            type: "error",
            message: "优惠价不能为空或输入大于0的优惠价"
          });
        } else {
          updateActivityGoods(data).then(res => {
            if (res.code == "200") {
              this.cancelgoodsClass()
            }
          });
        }
      }
    },
    // 取消
    cancelgoodsClass(){
      this.dialogShop.shopName=""
      this.dialogShop.commodityBrand=""
      this.dialogShop.commodityCategory=[""]
      this.goodsClass.dialog=false
    },
    // 分配的门店列表
    _distributionlistPage(pageSize, pageNum) {
      let Data = {
        pageNum: pageNum,
        pageSize: pageSize,
        businessId: this.merchantId,
        status: 0,
        nameOrCode: this.selectdatas.orgKey,
        type: "3"
      };
      selectBaseShopPageList(Data).then(res => {
        this.distribution.pageData.totalItems = res.data.pageTotal;
        this.shopList = res.data.list;
      });
    },
    // 门店查询
    searchSelectOrg() {
      if (this.nameType == "0") {
        this._distributionlistPage();
      } else {
        this._distribution(this.nameType,this.idType,this.activityName);
      }
    },
    // 分配
    _distribution(name, id='',activityName='') {
      this.nameType = name;
      this.idType=id;
      this.activityName=activityName
      if (name == "0") {
        
        this.Elastic = "选择门店";
        if (this.priceList.isSelect(2, this, "请先选择活动！")) {
          this.distribution.dialog = true;
          this.unallocates = false;
          this._distributionlistPage();
        }
      } else {
        this.activityIds = id;
        this.Elastic = "已分配门店-"+activityName;
        this.unallocates = true;
        this.distribution.dialog = true;
        let data = {
          activityId: id,
          shopName: this.selectdatas.orgKey,
        };
        distributionShopList(data).then(res => {
          if (res.code == "200") {
            // this.distribution.pageData.totalItems = res.data.pageTotal;
            if (res.data != null) {
              this.shopList = res.data;
            }else{
              this.shopList=[]
            }
            this.$refs.multipleTable.clearSelection();
          }
        });
      }
    },
    Sub() {
      this.selectdatas.orgKey=""
      this.distribution.dialog=false
      this.$refs.multipleTables.clearSelection();
      this.$refs.multipleTable.clearSelection();
    },
    // 立即分配
    immediateAllocation() {
      let shopIds = [];
      let activityIds = [];
      this.distribution.multipleSelectTable.forEach(i => {
        shopIds.push(i.id);
      });
      this.priceList.multipleSelectTable.forEach(i => {
        activityIds.push(i.id);
      });
      let data = {
        shopIds: shopIds.toString(),
        activityIds: activityIds.toString()
      };
      markettoLowerShop(data).then(res => {
        if (res.code == "200") {
          this.distribution.dialog = false;
          this.$refs.multipleTable.clearSelection();
          this.$refs.multipleTables.clearSelection()
          this.$message.success(res.msg);
          this.selectdatas.orgKey=""
        }else if(res.code=="10001"){
           this.$alert("同一活动时间内，同一商品不能出现在两个变价方案中~", res.msg, {
          confirmButtonText: '确定',
          center: true,
          callback: action => {
           this.tableget(this.priceList.pageData.pageSize, 1);
          }
         });
        }
      });
    },
    // 取消分配
    cancel(id = "") {
      let shopIds = [];
      this.distribution.multipleSelectTable.forEach(i => {
        shopIds.push(i.id);
      });
      let shopId;
      if (id != "") {
        shopId = id;
      } else {
        shopId = shopIds.toString();
      }
      let data = {
        activityId: this.activityIds,
        shopIds: shopId
      };
      if (id != "") {
        this.$confirm("确定要取消对本门店的分配吗？", {
          center: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false,
          closeOnPressEscape: false
        }).then(() => {
          cancelDistribution(data).then(res => {
            if (res.code == 200) {
              this._distribution(this.nameType,this.idType,this.activityName);
              this.$message.success(res.msg);
            }
          });
        });
      } else {
        if (this.distribution.isSelect(2, this, "请先选择门店！")) {
          this.$confirm("确定要取消对这些门店的分配吗？", {
            center: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            closeOnClickModal: false,
            closeOnPressEscape: false
          }).then(() => {
            cancelDistribution(data).then(res => {
              if (res.code == 200) {
                this._distribution(this.nameType,this.idType,this.activityName);
                this.$message.success(res.msg);
              }
            });
          });
        }
      }
    },
    // 点击查看编辑
    routerPush(type, param) {
      if (type == "0") {
        util.routerTo("/marketing-center/company-active/new-memberact", {
          showTab: param.showTab,
          id: param.id
        });
      }
      if (type == "1") {
        util.routerTo("/marketing-center/company-active/care-menberact", {
          showTab: param.showTab,
          id: param.id
        });
      }
    }
  }
};
</script>
<style lang="">
  .demo .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
/*打开时文字位置设置*/
.demo .el-switch__label--right {
  z-index: 1;
  right: -3px;
}
/*关闭时文字位置设置*/
.demo .el-switch__label--left {
  z-index: 1;
  left: 19px;
}
/*显示文字*/
.demo .el-switch__label.is-active {
  display: block;
}
.demo.el-switch .el-switch__core,
.demo.el-switch .el-switch__label {
  width: 50px !important;
  text-align: left;
}
</style>
